package com.jsoft.jsofted.framework.vo;

import com.jsoft.jsofted.framework.entity.TreeEntity;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

public class TreeMaker {
    private List<TreeEntity> entityList;

    private LinkedHashMap<Long, TreeNode> nodes;

    private List<TreeNode> tree;

    private TreeMaker(List<TreeEntity> list) {
        this.entityList = list;
    }

    public static List<TreeNode> makeTree(List<TreeEntity> entityList) {
        TreeMaker maker = new TreeMaker(entityList);
        maker._makeNodes();
        maker._makeTree();
        return maker.tree;
    }

    private void _makeNodes() {
        this.nodes = new LinkedHashMap();
        for (TreeEntity entity : entityList) {
            TreeNode node = new TreeNode();
            node.copyFrom(entity);

            this.nodes.put(node.getId(), node);
        }
    }

    private void _makeTree() {
        this.tree = new LinkedList();
        for (TreeEntity entity : entityList) {
            TreeNode node = this.nodes.get(entity.getId());
            TreeNode parentNode = this.nodes.get(node.getParentId());

            if (parentNode == null) {
                this.tree.add(node);
            } else {
                parentNode.addChild(node);
            }
        }
    }
}
